package com.product.controller;

import com.common.VO.SupermarketResult;
import com.common.VO.SysResult;
import com.common.domain.Product;
import com.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-05-12 14:45
 * @description
 * @copyright 2021
 */
@RestController
public class ProductController {
  @Autowired private ProductService productService;
  /**
   * 分页查询
   *
   * @param page 查询第几页
   * @param rows 查询几条记录
   * @return 查询的商品列表
   */
  @RequestMapping(value = "/pageManage", method = RequestMethod.GET)
  @ResponseBody
  public SupermarketResult queryPage(
      @RequestParam(value = "page", defaultValue = "1") int page,
      @RequestParam(value = "rows", defaultValue = "30") int rows) {
    return this.productService.queryByPage(page, rows);
  }
  /**
   * 商品查询
   *
   * @param productId 商品id
   * @return 查询的商品
   */
  @RequestMapping(value = "/item/{productId}", method = RequestMethod.GET)
  @ResponseBody
  public Product selectById(@PathVariable("productId") String productId) {
    try {
      return this.productService.queryByProductId(productId);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 商品新增
   *
   * @param product 新增的商品，productId为null
   * @return SysResult
   */
  @RequestMapping(value = "/save", method = RequestMethod.POST)
  @ResponseBody
  public SysResult addProduct(Product product) {
    try {
      this.productService.addProduct(product);
      return SysResult.ok();
    } catch (Exception e) {
      e.printStackTrace();
      return new SysResult(501, e.getMessage(), e);
    }
  }

  @RequestMapping(value = "/update", method = RequestMethod.PUT)
  @ResponseBody
  public SysResult updateProduct(Product product) {
    try {
      this.productService.updateProduct(product);
      return SysResult.ok();
    } catch (Exception e) {
      e.printStackTrace();
      return new SysResult(501, e.getMessage(), e);
    }
  }

  /**
   * 查询全部商品
   *
   * @return 全部商品列表
   */
  @RequestMapping(value = "/all", method = RequestMethod.GET)
  @ResponseBody
  public List<Product> all() {
    return this.productService.queryProducts();
  }
}
